package jmine.tec.persist.schema.impl.parsers;

import java.util.regex.Matcher;

import jmine.tec.persist.schema.impl.elements.PrimaryKeyElement;
import jmine.tec.persist.schema.impl.elements.Schema;

/**
 * Parser de primary key
 * 
 * @author lundberg
 */
public class PrimaryKeyParser extends AbstractSchemaElementParser<PrimaryKeyElement> {

    private static final int TABLE_NAME_GROUP_INDEX = 1;

    private static final int PK_NAME_GROUP_INDEX = 2;

    private static final int PK_COLUMNS_GROUP_INDEX = 3;

    /**
     * Construtor
     * @param schema schema
     */
    public PrimaryKeyParser(Schema schema) {
        super("alter\\s+table\\s+(" + TableParser.TABLE_NAME_REGEX  + ")\\s+add\\s+constraint\\s+(\\w+)\\s+primary\\s+key\\s+\\(([\\w\\s,]+)\\)", schema);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public PrimaryKeyElement doParse(Matcher matcher) {
        String table = matcher.group(TABLE_NAME_GROUP_INDEX);
        String pkName = matcher.group(PK_NAME_GROUP_INDEX);
        String[] columns = matcher.group(PK_COLUMNS_GROUP_INDEX).replaceAll("\\s", "").split(",");
        return new PrimaryKeyElement(pkName, table, columns, getSchema());
    }
}
